package com.sheeran.aichat.controller.deepseek;

import com.sheeran.aichat.exception.BusinessException;
import com.sheeran.aichat.utils.rest.ResponseCode;
import com.sheeran.aichat.utils.rest.WrappedResponseController;
import io.github.pigmesh.ai.deepseek.core.*;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Objects;

/**
 * @author: sheeran
 * @create: 2025/02/19
 */
@Api(tags = "DeepSeek-R1大模型")
@RequiredArgsConstructor
@RestController
@WrappedResponseController
@RequestMapping("/deepseek/chat")
public class DeepSeekController {

    private static final Logger log = LoggerFactory.getLogger(DeepSeekController.class);
    private final DeepSeekClient deepSeekClient;

    /**
     * 通过：http://localhost:8081/deepseek/chat/completions?userMessage=你好
     */
    @RequestMapping(value = "/completions", method = RequestMethod.GET)
    public Object chatCompletion(@RequestParam String userMessage) {
        SyncOrAsyncOrStreaming<String> stringSyncOrAsyncOrStreaming = deepSeekClient.chatCompletion(userMessage);
        return stringSyncOrAsyncOrStreaming.execute();
    }

    @RequestMapping(value = "/chat/{userMessage}", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseEntity<Object> chat(@PathVariable("userMessage") String userMessage) {
        ChatCompletionRequest builder = ChatCompletionRequest.builder()
                .model("deepseek-chat")
                .addUserMessage(userMessage)
                .build();
        Flux<ChatCompletionResponse> objectFlux = Flux.create((emitter) -> {
            StreamingResponseHandling var10000 = deepSeekClient.chatCompletion(builder).onPartialResponse(emitter::next);
            Objects.requireNonNull(emitter);
            StreamingCompletionHandling var3 = var10000.onComplete(emitter::complete);
            Objects.requireNonNull(emitter);
            var3.onError(emitter::error).execute();
        });
//        Flux<ChatCompletionResponse> chatCompletionResponseFlux = deepSeekClient.chatFluxCompletion(userMessage);
        ChatCompletionResponse chatCompletionResponse = null;
        try {
            chatCompletionResponse = objectFlux.blockFirst();
        } catch (Exception e) {
            log.error("Error in chat method:{}", e.getMessage());
            if (e.getMessage().contains("Insufficient Balance")) {
                return new ResponseEntity<>("账户余额不足，请充值后再试。", HttpStatus.PAYMENT_REQUIRED);
            }
        }
        return ResponseEntity.ok(chatCompletionResponse);
    }
}
